<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>消息WebSocket测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .panel {
            flex: 1;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 8px;
            padding: 8px;
            border-radius: 5px;
        }
        .message.sent {
            background-color: #dcf8c6;
            margin-left: 20%;
        }
        .message.received {
            background-color: #f1f0f0;
            margin-right: 20%;
        }
        .message.system {
            background-color: #ffecb3;
            text-align: center;
        }
        .controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        button {
            padding: 8px 12px;
            cursor: pointer;
        }
        input, select, textarea {
            padding: 8px;
            margin-bottom: 10px;
        }
        .status {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .user-list {
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
            min-height: 100px;
        }
        .online-user {
            padding: 5px;
            margin: 2px 0;
            background-color: #e8f5e9;
            border-radius: 3px;
            cursor: pointer;
        }
        .file-preview {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h1>消息WebSocket测试</h1>
    
    <div class="panel">
        <h2>连接设置</h2>
        <div class="controls">
            <div>
                <label for="username">用户名:</label>
                <input type="text" id="username" placeholder="输入用户名">
            </div>
            <div>
                <button id="connectBtn">连接</button>
                <button id="disconnectBtn" disabled>断开连接</button>
            </div>
            <div id="connectionStatus" class="status disconnected">未连接</div>
        </div>
    </div>
    
    <div class="container">
        <div class="panel">
            <h2>消息测试</h2>
            <div class="messages" id="messageContainer"></div>
            <div class="controls">
                <div>
                    <label for="recipient">接收者:</label>
                    <input type="text" id="recipient" placeholder="接收者用户名">
                </div>
                <div>
                    <label for="messageType">消息类型:</label>
                    <select id="messageType">
                        <option value="TEXT">文本消息</option>
                        <option value="IMAGE">图片消息</option>
                        <option value="AUDIO">音频消息</option>
                        <option value="VIDEO">视频消息</option>
                        <option value="FILE">文件消息</option>
                        <option value="FRIEND_REQUEST">好友请求</option>
                        <option value="FRIEND_RESPONSE">好友响应</option>
                        <option value="TYPING">正在输入</option>
                    </select>
                </div>
                <div>
                    <label for="messageContent">消息内容:</label>
                    <textarea id="messageContent" placeholder="输入消息内容"></textarea>
                </div>
                <div id="fileUploadContainer" style="display: none;">
                    <label for="fileUpload">选择文件:</label>
                    <input type="file" id="fileUpload">
                    <div id="filePreviewContainer"></div>
                </div>
                <div>
                    <button id="sendBtn" disabled>发送消息</button>
                </div>
            </div>
        </div>
        
        <div class="panel">
            <h2>在线用户</h2>
            <div class="user-list" id="userList"></div>
            
            <h2>朋友圈测试</h2>
            <div class="controls">
                <div>
                    <label for="momentContent">朋友圈内容:</label>
                    <textarea id="momentContent" placeholder="输入朋友圈内容"></textarea>
                </div>
                <div>
                    <button id="postMomentBtn" disabled>发布朋友圈</button>
                </div>
                
                <div style="margin-top: 20px;">
                    <label for="momentId">朋友圈ID:</label>
                    <input type="text" id="momentId" placeholder="朋友圈ID">
                </div>
                <div>
                    <label for="momentOwner">朋友圈所有者:</label>
                    <input type="text" id="momentOwner" placeholder="朋友圈所有者">
                </div>
                <div>
                    <label for="commentContent">评论内容:</label>
                    <textarea id="commentContent" placeholder="输入评论内容"></textarea>
                </div>
                <div>
                    <button id="likeBtn" disabled>点赞</button>
                    <button id="commentBtn" disabled>评论</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let currentUser = null;
        let onlineUsers = new Set();
        
        // DOM元素
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const sendBtn = document.getElementById('sendBtn');
        const postMomentBtn = document.getElementById('postMomentBtn');
        const likeBtn = document.getElementById('likeBtn');
        const commentBtn = document.getElementById('commentBtn');
        const usernameInput = document.getElementById('username');
        const recipientInput = document.getElementById('recipient');
        const messageTypeSelect = document.getElementById('messageType');
        const messageContentInput = document.getElementById('messageContent');
        const momentContentInput = document.getElementById('momentContent');
        const momentIdInput = document.getElementById('momentId');
        const momentOwnerInput = document.getElementById('momentOwner');
        const commentContentInput = document.getElementById('commentContent');
        const messageContainer = document.getElementById('messageContainer');
        const connectionStatus = document.getElementById('connectionStatus');
        const userList = document.getElementById('userList');
        const fileUploadContainer = document.getElementById('fileUploadContainer');
        const fileUpload = document.getElementById('fileUpload');
        const filePreviewContainer = document.getElementById('filePreviewContainer');
        
        // 事件监听
        connectBtn.addEventListener('click', connect);
        disconnectBtn.addEventListener('click', disconnect);
        sendBtn.addEventListener('click', sendMessage);
        postMomentBtn.addEventListener('click', postMoment);
        likeBtn.addEventListener('click', likeMoment);
        commentBtn.addEventListener('click', commentMoment);
        messageTypeSelect.addEventListener('change', handleMessageTypeChange);
        fileUpload.addEventListener('change', handleFileSelect);
        
        // 连接WebSocket
        function connect() {
            const username = usernameInput.value.trim();
            if (!username) {
                addSystemMessage('请输入用户名');
                return;
            }
            
            currentUser = username;
            
            // 构建WebSocket URL，添加用户名作为查询参数
            const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${wsProtocol}//${window.location.host}/MessagingWebSocketServer?username=${encodeURIComponent(username)}`;
            
            try {
                ws = new WebSocket(wsUrl);
                
                ws.onopen = function() {
                    setConnectionStatus(true);
                    addSystemMessage(`已连接到消息服务器，用户名: ${username}`);
                };
                
                ws.onmessage = function(event) {
                    handleIncomingMessage(event.data);
                };
                
                ws.onclose = function() {
                    setConnectionStatus(false);
                    addSystemMessage('与服务器的连接已关闭');
                };
                
                ws.onerror = function(error) {
                    setConnectionStatus(false);
                    addSystemMessage('WebSocket错误: ' + error);
                    console.error('WebSocket错误:', error);
                };
            } catch (error) {
                addSystemMessage('连接错误: ' + error.message);
                console.error('连接错误:', error);
            }
        }
        
        // 断开连接
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
                currentUser = null;
                onlineUsers.clear();
                updateUserList();
            }
        }
        
        // 设置连接状态
        function setConnectionStatus(isConnected) {
            if (isConnected) {
                connectionStatus.textContent = '已连接';
                connectionStatus.className = 'status connected';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                sendBtn.disabled = false;
                postMomentBtn.disabled = false;
                likeBtn.disabled = false;
                commentBtn.disabled = false;
            } else {
                connectionStatus.textContent = '未连接';
                connectionStatus.className = 'status disconnected';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                sendBtn.disabled = true;
                postMomentBtn.disabled = true;
                likeBtn.disabled = true;
                commentBtn.disabled = true;
            }
        }
        
        // 发送消息
        function sendMessage() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addSystemMessage('未连接到服务器');
                return;
            }
            
            const recipient = recipientInput.value.trim();
            if (!recipient) {
                addSystemMessage('请输入接收者用户名');
                return;
            }
            
            const messageType = messageTypeSelect.value;
            const content = messageContentInput.value.trim();
            
            if (!content && ['TEXT', 'FRIEND_REQUEST', 'FRIEND_RESPONSE'].includes(messageType)) {
                addSystemMessage('请输入消息内容');
                return;
            }
            
            const message = {
                type: messageType,
                toUser: recipient,
                content: content
            };
            
            // 处理文件上传
            if (['IMAGE', 'AUDIO', 'VIDEO', 'FILE'].includes(messageType) && fileUpload.files.length > 0) {
                const file = fileUpload.files[0];
                
                // 先发送文件传输请求
                const fileTransferRequest = {
                    type: 'FILE_TRANSFER_REQUEST',
                    toUser: recipient,
                    content: file.name,
                    fileType: file.type,
                    fileSize: file.size
                };
                
                ws.send(JSON.stringify(fileTransferRequest));
                addSentMessage(`文件传输请求: ${file.name} (${formatFileSize(file.size)})`);
                
                // 文件数据会在收到服务器的READY_FOR_TRANSFER响应后发送
                return;
            }
            
            ws.send(JSON.stringify(message));
            addSentMessage(`${messageType}: ${content}`);
            messageContentInput.value = '';
        }
        
        // 发布朋友圈
        function postMoment() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addSystemMessage('未连接到服务器');
                return;
            }
            
            const content = momentContentInput.value.trim();
            if (!content) {
                addSystemMessage('请输入朋友圈内容');
                return;
            }
            
            const message = {
                type: 'MOMENT',
                content: content
            };
            
            ws.send(JSON.stringify(message));
            addSentMessage(`发布朋友圈: ${content}`);
            momentContentInput.value = '';
        }
        
        // 点赞朋友圈
        function likeMoment() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addSystemMessage('未连接到服务器');
                return;
            }
            
            const momentId = momentIdInput.value.trim();
            const momentOwner = momentOwnerInput.value.trim();
            
            if (!momentId) {
                addSystemMessage('请输入朋友圈ID');
                return;
            }
            
            if (!momentOwner) {
                addSystemMessage('请输入朋友圈所有者');
                return;
            }
            
            const message = {
                type: 'LIKE',
                toUser: momentOwner,
                momentId: momentId
            };
            
            ws.send(JSON.stringify(message));
            addSentMessage(`点赞朋友圈: ${momentId}`);
        }
        
        // 评论朋友圈
        function commentMoment() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addSystemMessage('未连接到服务器');
                return;
            }
            
            const momentId = momentIdInput.value.trim();
            const momentOwner = momentOwnerInput.value.trim();
            const content = commentContentInput.value.trim();
            
            if (!momentId) {
                addSystemMessage('请输入朋友圈ID');
                return;
            }
            
            if (!momentOwner) {
                addSystemMessage('请输入朋友圈所有者');
                return;
            }
            
            if (!content) {
                addSystemMessage('请输入评论内容');
                return;
            }
            
            const message = {
                type: 'COMMENT',
                toUser: momentOwner,
                momentId: momentId,
                content: content
            };
            
            ws.send(JSON.stringify(message));
            addSentMessage(`评论朋友圈: ${content}`);
            commentContentInput.value = '';
        }
        
        // 处理消息类型变化
        function handleMessageTypeChange() {
            const messageType = messageTypeSelect.value;
            
            // 显示/隐藏文件上传控件
            if (['IMAGE', 'AUDIO', 'VIDEO', 'FILE'].includes(messageType)) {
                fileUploadContainer.style.display = 'block';
            } else {
                fileUploadContainer.style.display = 'none';
            }
        }
        
        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            filePreviewContainer.innerHTML = '';
            
            // 预览图片
            if (file.type.startsWith('image/')) {
                const img = document.createElement('img');
                img.classList.add('file-preview');
                img.file = file;
                filePreviewContainer.appendChild(img);
                
                const reader = new FileReader();
                reader.onload = (function(aImg) {
                    return function(e) {
                        aImg.src = e.target.result;
                    };
                })(img);
                reader.readAsDataURL(file);
            } else {
                // 显示文件信息
                const fileInfo = document.createElement('div');
                fileInfo.textContent = `${file.name} (${formatFileSize(file.size)})`;
                filePreviewContainer.appendChild(fileInfo);
            }
        }
        
        // 处理传入的消息
        function handleIncomingMessage(data) {
            try {
                const message = JSON.parse(data);
                console.log('收到消息:', message);
                
                switch (message.type) {
                    case 'TEXT':
                    case 'IMAGE':
                    case 'AUDIO':
                    case 'VIDEO':
                    case 'FILE':
                        addReceivedMessage(`${message.fromUser}: ${message.content || message.type}`);
                        break;
                    
                    case 'SYSTEM':
                        addSystemMessage(message.content);
                        
                        // 处理文件传输准备就绪
                        if (message.status === 'READY_FOR_TRANSFER' && message.fileId) {
                            handleFileTransferReady(message.fileId);
                        }
                        break;
                    
                    case 'USER_STATUS':
                        const user = message.fromUser;
                        const isOnline = message.content === 'online';
                        
                        if (isOnline) {
                            onlineUsers.add(user);
                            addSystemMessage(`${user} 已上线`);
                        } else {
                            onlineUsers.delete(user);
                            addSystemMessage(`${user} 已下线`);
                        }
                        
                        updateUserList();
                        break;
                    
                    case 'FRIEND_REQUEST':
                        addReceivedMessage(`收到好友请求: ${message.fromUser}`);
                        break;
                    
                    case 'FRIEND_RESPONSE':
                        const accepted = message.content === 'accept';
                        addReceivedMessage(`好友请求${accepted ? '已接受' : '已拒绝'}: ${message.fromUser}`);
                        break;
                    
                    case 'MOMENT':
                        addReceivedMessage(`朋友圈: ${message.fromUser} 发布了: ${message.content} (ID: ${message.momentId})`);
                        break;
                    
                    case 'LIKE':
                        addReceivedMessage(`${message.fromUser} 点赞了你的朋友圈 (ID: ${message.momentId})`);
                        break;
                    
                    case 'COMMENT':
                        addReceivedMessage(`${message.fromUser} 评论了你的朋友圈: ${message.content} (ID: ${message.momentId})`);
                        break;
                    
                    case 'TYPING':
                        addSystemMessage(`${message.fromUser} 正在输入...`);
                        break;
                    
                    case 'FILE_TRANSFER_REQUEST':
                        addReceivedMessage(`${message.fromUser} 想要发送文件: ${message.content} (${formatFileSize(message.fileSize)})`);
                        break;
                    
                    case 'FILE_METADATA':
                        addReceivedMessage(`正在接收文件: ${message.content} (${formatFileSize(message.fileSize)})`);
                        break;
                }
            } catch (error) {
                console.error('解析消息失败:', error);
                addSystemMessage('解析消息失败: ' + error.message);
            }
        }
        
        // 处理文件传输准备就绪
        function handleFileTransferReady(fileId) {
            if (fileUpload.files.length === 0) return;
            
            const file = fileUpload.files[0];
            const reader = new FileReader();
            
            reader.onload = function(event) {
                const arrayBuffer = event.target.result;
                // 发送二进制数据
                ws.send(arrayBuffer);
                addSystemMessage(`文件 "${file.name}" 已发送`);
            };
            
            reader.onerror = function(error) {
                addSystemMessage('读取文件失败: ' + error);
            };
            
            reader.readAsArrayBuffer(file);
        }
        
        // 添加发送的消息到消息容器
        function addSentMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message sent';
            messageDiv.textContent = text;
            messageContainer.appendChild(messageDiv);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        // 添加接收的消息到消息容器
        function addReceivedMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message received';
            messageDiv.textContent = text;
            messageContainer.appendChild(messageDiv);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        // 添加系统消息到消息容器
        function addSystemMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message system';
            messageDiv.textContent = text;
            messageContainer.appendChild(messageDiv);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        // 更新用户列表
        function updateUserList() {
            userList.innerHTML = '';
            
            if (onlineUsers.size === 0) {
                const noUsersDiv = document.createElement('div');
                noUsersDiv.textContent = '没有其他在线用户';
                userList.appendChild(noUsersDiv);
                return;
            }
            
            onlineUsers.forEach(user => {
                if (user !== currentUser) {
                    const userDiv = document.createElement('div');
                    userDiv.className = 'online-user';
                    userDiv.textContent = user;
                    userDiv.addEventListener('click', () => {
                        recipientInput.value = user;
                    });
                    userList.appendChild(userDiv);
                }
            });
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
            if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
            return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
        }
        
        // 初始化
        handleMessageTypeChange();
    </script>
</body>
</html> 